# -*- coding: utf-8 -*-
__author__ = 'vladbranzei'

import sys, os
from pymongo import MongoClient
from pymongo.errors import DuplicateKeyError

def create(host, port, username=None, password=None):
    client = MongoClient(host, int(port))
    db = client.portal
    if username:
        client.admin.authenticate(username, password)
    collection = db.users

    try:
        result = collection.insert({'init':'init'})
        if result:
            print('portal.users created')

        else:
            print('an error occurred while creating users')

    except DuplicateKeyError as e:
        print("portal.users already exists")

    return None

if __name__ == "__main__":
    if len(sys.argv) == 3:
        host = sys.argv[1].split('=')[1]
        port = sys.argv[2].split('=')[1]
        print("host = " + host)
        print("port = " + port)
        create(host, port)
    else:
        host = os.environ['OPENSHIFT_MONGODB_DB_HOST']
        port = os.environ['OPENSHIFT_MNGODB_DB_PORT']
        username = os.environ['OPENSHIFT_MONGODB_DB_USERNAME']
        password = os.environ['OPENSHIFT_MONGODB_DB_PASSWORD']
        print('host = ' + host + ' port = ' + port)
        create(host, port, username, password)


